<?php

class Workset_Controller_Action_Helper_FileTransfer extends Zend_Controller_Action_Helper_Abstract {

	protected $_groupMultifiles = true;

	protected $_receiveAll = true;

	protected $_files = array();

	protected $_uploadedFiles = array();

    function direct($path = null, $filter = null, $groupMultifiles = true) {
        return $this->receive($path, $filter, $groupMultifiles);
    }

	function setFiles(array $files) {
		$this->_files = $files;
		return $this;
	}

	function addFile($file) {
		$this->_files[] = $file;
		return $this;
	}

	function addFiles(array $files) {
		$this->_files = array_merge($this->_files, $files);
		return $this;
	}

	function setIsReceiveAll($flag = true) {
		$this->_receiveAll = (bool)$flag;
	}

	protected function _attachToArray($key, $value, &$array) {
		//detect format [element]_[number]_[n]_
		if (strrpos($key, '_') === strlen($key) - 1) {
            unset($array[$key]);

			$parts = explode("_", $key);
            $parts = array_filter($parts);

			if ($parts) {

				$key = null;
                $subkey = array();
                $valueId = 0;

                foreach ($parts as $part) {
                    if (null === $key) {
                       $key = $part;
                    } elseif (!isInt($part)) {
                       $subkey[] = $part;
                    } elseif (!$valueId) {
                       $valueId = (int)$part;
                    }
                }

                if ($subkey) {
                    $subkey = implode("_", $subkey);
                    $array[$key][$subkey] = $value;

                } else {
                    $array[$key][$valueId] = $value;
                }

			} else {
				throw new Zend_File_Transfer_Exception("No detected form name '$key'");
			}
		} else {
			$array[$key] = $value;
		}
	}

    function receive($path = null, $filter = null, $groupMultifiles = true) {

        if (null === $path) {
            $path = UPLOAD_FILE_PATH;
        }

		if ($this->_uploadedFiles) {
			$this->_files = array_diff((array)$this->_files, $this->_uploadedFiles);
		}

		if (!$this->_receiveAll && empty($this->_files)) {
			return array();
		}

        $uploader = new Workset_File_Transfer_Adapter_Http();
        $fileinfo = $uploader->getFileInfo( ($this->_files ? $this->_files : null) );

		//dump($this->_files);
		//dump($this->_uploadedFiles);
		//dump($fileinfo);

		if ($this->_files) {
			$this->_uploadedFiles = array_merge($this->_uploadedFiles, $this->_files);
			$this->_files = array();
		}

        $returnInfo = array();
		$noUploadedFiles = array();

		//не обрабатываем файлы, которые не были загружены (незаполненные поля в input=file)
        foreach ($fileinfo as $key => $file) {
            if ($file['error'] == UPLOAD_ERR_NO_FILE) {
                unset($fileinfo[$key]);
				$noUploadedFiles[$key] = null;
            }
        }

        if (!empty($fileinfo)) {
            $uploader->setDestination(array($path, $this->getRequest()->getModuleName()));

            if ($fileinfo && !$uploader->receive(array_keys($fileinfo))) {

                $messages = $uploader->getMessages();
                $messages = implode('\n', $messages);
                throw new Zend_File_Transfer_Exception($messages);
            }
        }

        $groupMultifiles = $groupMultifiles && $groupMultifiles == $this->_groupMultifiles;
		
        $fileinfo = $uploader->getFileInfo(array_keys($fileinfo));

		//добавляем в результатирующий спискок незагруженные файлы
		if (!empty($noUploadedFiles)) {
			$fileinfo = array_merge($fileinfo, $noUploadedFiles);
		}

        //dump($fileinfo);

		//если нужен другой формат результатирующего набора
        if (null !== $filter) {

            if ($filter instanceof Closure) {
                return $filter($fileinfo);

            } elseif ($filter instanceof Zend_Filter) {
                return $filter->filter($fileinfo);

            } else {
                throw new Zend_File_Transfer_Exception('Type of filter is wrong');
            }

        } else {
            foreach ($fileinfo as $key => $content) {
                if ($content['received'] != true) {
                    $params = null;
                } else {
                    $params = Workset_File_Info_Helper::createInfo($content['destination'].'/'.$content['name']);
                }			

				if ($groupMultifiles) {
					
					//detect format [element]_[number]_[n]_
					$this->_attachToArray($key, $params, $returnInfo);

				} else {
					$returnInfo[$key] = $params;
				}
            }
        }

		//dump($returnInfo);
		
        return $returnInfo;
    }

}

?>